import turtle
import math
import time

# 设置高清显示
screen = turtle.Screen()
screen.title("鳄鱼追人模拟 - 高清优化版")
screen.setup(width=800, height=800, startx=0, starty=0)
screen.bgcolor("white")
screen.tracer(0)  # 关闭自动刷新
screen.delay(0)  # 消除绘制延迟

# 等边三角形参数
triangle_size = 300  # 三角形边长

# 初始化人和鳄鱼
person = turtle.Turtle()
person.shape("circle")
person.color("blue")
person.shapesize(0.4)  # 适当大小的点
person.penup()
person.pensize(2)  # 更粗的轨迹线
person.speed(0)  # 最快绘制速度

crocodiles = []
colors = ["red", "green", "purple"]
speeds = [20, 20, 15]  # 鳄鱼速度 (m/s)
person_speed = 10  # 人的速度 (m/s)


# 计算等边三角形的顶点坐标
def calculate_triangle_vertices(size):
    height = size * math.sqrt(3) / 2
    return [
        (0, height * 2 / 3),  # 顶部顶点
        (-size / 2, -height / 3),  # 左下顶点
        (size / 2, -height / 3)  # 右下顶点
    ]


# 初始化位置 - 使用高清绘制
vertices = calculate_triangle_vertices(triangle_size)
for i in range(3):
    croc = turtle.Turtle()
    croc.shape("circle")
    croc.color(colors[i])
    croc.shapesize(0.5)  # 清晰可见的点
    croc.penup()
    croc.pensize(2)  # 更粗的轨迹线
    croc.speed(0)  # 最快绘制速度
    croc.goto(vertices[i])
    croc.pendown()
    crocodiles.append(croc)

# 人的初始位置
person.goto(0, 0)
person.pendown()


# 计算两点之间距离
def distance(p1, p2):
    return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)


# 计算人被抓住的时间（优化版）
def time_until_capture(person_pos, person_dir, croc_positions):
    max_time = 0
    for i, (croc_pos, croc_speed) in enumerate(zip(croc_positions, speeds)):
        dx = person_pos[0] - croc_pos[0]
        dy = person_pos[1] - croc_pos[1]
        dist = distance(person_pos, croc_pos)

        if dist < 5:  # 捕获距离阈值
            return 0

        # 计算相对速度向量
        person_vx = person_speed * math.cos(person_dir)
        person_vy = person_speed * math.sin(person_dir)
        croc_vx = croc_speed * dx / dist
        croc_vy = croc_speed * dy / dist

        rel_vx = croc_vx - person_vx
        rel_vy = croc_vy - person_vy

        # 计算捕获时间（向量投影）
        denominator = rel_vx ** 2 + rel_vy ** 2
        if denominator < 1e-6:  # 避免除以零
            return float('inf')

        time_to_capture = (dx * rel_vx + dy * rel_vy) / denominator

        if time_to_capture > max_time:
            max_time = time_to_capture

    return max(max_time, 0)  # 确保不返回负值


# 寻找最佳逃跑方向（360度精细检测）
def find_best_direction(person_pos, croc_positions):
    best_dir = 0
    best_time = 0

    for i in range(360):  # 每度检测一次
        angle = math.radians(i)
        new_x = person_pos[0] + person_speed * math.cos(angle)
        new_y = person_pos[1] + person_speed * math.sin(angle)

        current_time = time_until_capture((new_x, new_y), angle, croc_positions)

        if current_time > best_time:
            best_time = current_time
            best_dir = angle

    return best_dir


# 主模拟循环（高清优化版）
def simulate():
    person_pos = [0, 0]
    croc_positions = [vertices[i] for i in range(3)]
    step_count = 0

    # 初始显示
    screen.update()
    time.sleep(1)  # 初始暂停

    while step_count < 60:  # 最多模拟60秒
        step_count += 1

        # 获取当前鳄鱼位置
        current_croc_pos = [croc.pos() for croc in crocodiles]

        # 寻找最佳方向
        best_dir = find_best_direction(person_pos, current_croc_pos)

        # 移动人
        person.setheading(math.degrees(best_dir))
        person.forward(person_speed)
        person_pos = [person.xcor(), person.ycor()]

        # 检查捕获
        for i, croc in enumerate(crocodiles):
            if distance(person_pos, croc.pos()) < 5:
                print(f"人在第{step_count}秒被鳄鱼{i + 1}抓住!")
                screen.update()
                turtle.done()
                return

        # 移动鳄鱼
        for i, croc in enumerate(crocodiles):
            croc_pos = croc.pos()
            dx = person_pos[0] - croc_pos[0]
            dy = person_pos[1] - croc_pos[1]
            dist = distance(person_pos, croc_pos)

            move_dist = min(speeds[i], dist)
            if move_dist > 0:
                croc.setheading(math.degrees(math.atan2(dy, dx)))
                croc.forward(move_dist)

        # 高清渲染
        screen.update()
        time.sleep(0.25)  # 流畅的动画速度

    print("人成功逃脱60秒!")
    turtle.done()


# 启动模拟
simulate()